<template>
  <a-card>
    <a-form>
      <a-form-item label="企业名称">
        <a-space>
          <a-input v-model:value="search" placeholder="请输入企业名称"></a-input>
          <a-button type="primary" @click="searchByName">查询</a-button>
        </a-space>
      </a-form-item>
      <a-divider />
      <a-button style="margin-bottom: 20px" type="primary" @click="addenterp">添加企业</a-button>
      <a-table
        :rowKey="(item) => item.id"
        :dataSource="tableData"
        :columns="columns"
        @expand="handleExpand"
        :pagination="{
          total: total,
          current: params.page,
          'show-total': showTotal,
          showQuickJumper: true,
          pageSizeOptions: ['5', '10', '15', '20'],
          pageSize: params.pageSize,
          onChange: changeCurrent,
          'show-size-changer': true
        }"
      >
        <template #expandedRowRender="{ record }">
          <a-table
            :pagination="false"
            :columns="incolumn"
            :dataSource="record.detailData"
            :rowKey="(item) => item.id"
          >
            <template #bodyCell="{ record, column }">
              <template v-if="column.dataIndex === 'timer'">
                {{ record.startTime }}至{{ record.endTime }}
              </template>
              <template v-if="column.dataIndex === 'status'">
                <div
                  :class="{
                    active1: record.status === 0,
                    active2: record.status === 1,
                    active3: record.status === 2,
                    active4: record.status === 3
                  }"
                >
                  {{
                    record.status === 0
                      ? '待生效'
                      : record.status === 1
                      ? '生效中'
                      : record.status === 2
                      ? '已到期'
                      : record.status === 3
                      ? '已退租'
                      : ''
                  }}
                </div>
              </template>
              <template v-if="column.dataIndex === 'inopera'">
                <a-button v-if="record.status === 1" type="link">续租</a-button>
                <a-button disabled v-else type="link">续租</a-button>
                <a-button
                  v-if="record.status === 1 || record.status === 0"
                  @click="putEnterpTableDataAPI(record.id)"
                  type="link"
                  >退租</a-button
                >
                <a-button disabled v-else type="link">退租</a-button>
                <a-button
                  v-if="record.status === 2 || record.status === 3"
                  @click="delTableDataAPI(record.id)"
                  type="link"
                  >删除</a-button
                >
                <a-button v-else disabled type="link">删除</a-button>
              </template>
            </template>
          </a-table>
        </template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'operation'">
            <a-button type="link">添加合同</a-button>
            <a-button type="link" @click="router.push(`/examine/${record.id}`)">查看</a-button>
            <a-button type="link" @click="router.push(`/editor/${record.id}`)">编辑</a-button>
            <a-button type="link" v-if="record.existContractFlag === 1" disabled>删除</a-button>
            <a-popconfirm
              v-else
              title="您确定要删除这项记录吗?"
              @confirm="confirm(e, record.id)"
              ok-text="Yes"
              cancel-text="No"
            >
              <a-button type="link">删除</a-button>
            </a-popconfirm>
          </template>
          <template v-if="column.dataIndex === 'status'">
            <span v-if="record.status === 0">闲置中</span>
            <span v-else>租赁中</span>
          </template>
        </template>
      </a-table>

      <!-- <a-table
        :pagination="{ defaultPageSize: 999, hideOnSinglePage: true }"
        :columns="columns"
        slot="expandedRowRender"
        slot-scope="AAAAAAAAAAAA"
        :dataSource="AAAAAAAAAAAA.groupItem"
        :rowKey="(item) => item.pushuserName"
        :locale="{ emptyText: '该类别 暂无节点' }"
      >
        <template v-slot:sex="text">{{ text || '你是太监吗' }}</template>
      </a-table> -->

      <!-- <a-table
        :pagination="{ defaultPageSize: 999, hideOnSinglePage: true }"
        :columns="outColumns"
        bordered
        :dataSource="dataGroups"
        :rowKey="(item) => item.groupId"
      >
        <template #expandedRowRender="{ record }">
          <a-table
            :pagination="{ defaultPageSize: 999, hideOnSinglePage: true }"
            :columns="testcolumns"
            :dataSource="record.groupItem"
            :rowKey="(item) => item.pushuserName"
          >
            <template #timer="{ record }">{{ record.startTime }}</template>
          </a-table>
        </template>
      </a-table> -->
    </a-form>
  </a-card>
  <a-button></a-button>

  <a-modal
    @cancel="cancleOpert"
    :title="isEdit ? '编辑楼宇' : '添加楼宇'"
    v-model:visible="visible"
    :footer="null"
  >
    <a-form
      ref="formRef"
      :model="operatTable"
      :label-col="{ span: 5 }"
      scrollToFirstError
      layout="vertical"
      @finish="onFinish"
    >
      <a-form-item
        :rules="[{ required: true, message: '楼宇名称不能为空哦帕~!', trigger: 'blur' }]"
        name="name"
        label="楼宇名称"
      >
        <a-input
          v-model:value="operatTable.name"
          size="mini"
          placeholder="请输入楼宇名称"
        ></a-input>
      </a-form-item>
      <a-form-item
        :rules="[{ required: true, message: '楼宇层数不能为空哦帕~!', trigger: 'blur' }]"
        name="floors"
        label="楼宇层数"
      >
        <a-input-number
          size="mini"
          style="width: 100%"
          v-model:value="operatTable.floors"
          placeholder="请输入楼宇层数"
        ></a-input-number>
      </a-form-item>
      <a-form-item
        :rules="[{ required: true, message: '在管面积不能为空哦帕~!', trigger: 'blur' }]"
        name="area"
        label="在管面积"
      >
        <a-input-number
          size="mini"
          style="width: 100%"
          v-model:value="operatTable.area"
          placeholder="请输入在管面积"
        ></a-input-number>
      </a-form-item>
      <a-form-item
        :rules="[{ required: true, message: '物业费不能为空哦帕~!', trigger: 'blur' }]"
        name="propertyFeePrice"
        label="物业费"
      >
        <a-input-number
          v-model:value="operatTable.propertyFeePrice"
          size="mini"
          style="width: 100%"
          placeholder="请输入物业费"
        ></a-input-number>
      </a-form-item>
      <a-form-item style="text-align: center">
        <a-space>
          <a-button html-type="submit" type="primary">确认</a-button>
          <a-button @click="cancleOpert">取消</a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </a-modal>

  <a-modal
    @cancel="cancleOpert"
    :title="isEdit ? '编辑楼宇' : '添加楼宇'"
    v-model:visible="visible"
    :footer="null"
  >
    <a-form
      ref="formRef"
      :model="innerTable"
      :label-col="{ span: 5 }"
      scrollToFirstError
      layout="vertical"
      @finish="onFinish"
    >
      <a-form-item
        :rules="[{ required: true, message: '楼宇名称不能为空哦帕~!', trigger: 'blur' }]"
        name="name"
        label="租赁楼宇"
      >
        <a-input
          v-model:value="operatTable.name"
          size="mini"
          placeholder="请输入楼宇名称"
        ></a-input>
      </a-form-item>
      <a-form-item
        :rules="[{ required: true, message: '楼宇层数不能为空哦帕~!', trigger: 'blur' }]"
        name="floors"
        label="租赁起止日期"
      >
        <a-input-number
          size="mini"
          style="width: 100%"
          v-model:value="operatTable.floors"
          placeholder="请输入楼宇层数"
        ></a-input-number>
      </a-form-item>
      <a-form-item
        :rules="[{ required: true, message: '在管面积不能为空哦帕~!', trigger: 'blur' }]"
        name="area"
        label="租赁合同"
      >
        <a-input-number
          size="mini"
          style="width: 100%"
          v-model:value="operatTable.area"
          placeholder="请输入在管面积"
        ></a-input-number>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>
import { hint } from '@/hooks/hint.js'
import { reactive, onMounted, ref } from 'vue'
import { fixTable, addTable, delTableData } from '@/api/user.js'
import {
  getEnterp,
  getDetailById,
  delEnterpTableData,
  putEnterpTableData
} from '@/api/businessman.js'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const operatTable = reactive({
  area: null,
  name: '',
  floors: null,
  propertyFeePrice: null
})
const innerTable = ref({
  buildingId: null,
  contractId: null,
  contractUrl: '',
  endTime: '',
  enterpriseId: null,
  startTime: '',
  type: 1
})
const rowrecord = ref(null)
const search = ref(null)
//表单ref
const formRef = ref(null)
let total = ref(null)
const showTotal = () => {
  return `总共${total.value}条`
}

// @finishFailed="onFinishFailed"

const isEdit = ref(false)
const visible = ref(false)
const params = reactive({
  page: 1,
  pageSize: 10
})
// const expandedRowKeys = ref('1')
const tableData = ref([])

const getEnterpData = async () => {
  const res = await getEnterp(params)
  console.log(res)
  tableData.value = res.data.rows.map((el, index) => ({
    ...el,
    index: (params.page - 1) * params.pageSize + index + 1,
    detailData: [
      // {
      //   buildingId: 1633,
      //   buildingName: '那你接口',
      //   endTime: '2023-08-16',
      //   exitFlag: 1,
      //   id: 989,
      //   renewFlag: 0,
      //   startTime: '2023-07-21',
      //   status: 0
      // }
    ]
  }))
  console.log(res.data.rows)
  total.value = res.data.total
}

onMounted(() => {
  getEnterpData()
  //    = res.data.rows
})
const confirm = async (e, id) => {
  await delTableData(id)
}
const changeCurrent = async (page, pageSize) => {
  params.page = page
  params.pageSize = pageSize
  await getEnterpData()
}

// 删除用户
const delTableDataAPI = async (id) => {
  console.log(123)
  const { Confirm, msg } = hint()
  try {
    await Confirm('是否确认删除当前合同?')
    console.log(id)
    await delEnterpTableData(id)
    msg('success', '删除合同成功')
    // await getEnterpData()
    await getDetail(rowrecord.value)
  } catch (e) {
    console.log(e)
  }
}
//修改数据
const putEnterpTableDataAPI = async (id) => {
  console.log(123)
  const { Confirm, msg } = hint()
  try {
    await Confirm('退租不可撤回，是否确认退租当前楼宇?')
    console.log(id)
    await putEnterpTableData(id)
    msg('success', '退租成功')

    await getDetail(rowrecord.value)
    // await getEnterpData()
    console.log('1')
  } catch (e) {
    console.log(e)
  }
}

// const editInfo = (row) => {
//   // operatTable.value = row
//   isEdit.value = true
//   operatTable.name = row.name
//   operatTable.area = row.area
//   operatTable.propertyFeePrice = row.propertyFeePrice
//   operatTable.floors = row.floors
//   operatTable.id = row.id
//   visible.value = true
// }
const cancleOpert = () => {
  formRef.value?.resetFields()
  visible.value = false
}
const onFinish = async () => {
  if (isEdit.value) {
    console.log(operatTable)
    await fixTable(operatTable)
    message.success('修改成功')
  } else {
    delete operatTable?.id
    console.log(operatTable)
    await addTable(operatTable)
    message.success('添加成功')
  }
  formRef.value?.resetFields()
  visible.value = false
  getEnterpData()
}

const searchByName = async () => {
  params.name = search
  params.page = 1
  await getEnterpData()
  delete params.name
}
const addenterp = () => {
  router.push('/addenterprise')
}
const getDetail = async (row) => {
  const res = await getDetailById(row.id)
  rowrecord.value = row
  row.detailData = res.data
  console.log(row.detailData)
}
const handleExpand = async (expanded, record) => {
  if (expanded && record.detailData?.length === 0) {
    await getDetail(record)
  }
  console.log(record)
}
const incolumn = [
  {
    title: '租赁楼宇',
    dataIndex: 'buildingName'
  },
  {
    title: '租赁起止时间',
    dataIndex: 'timer',
    scopedSlots: { customRender: 'timer' }
  },
  {
    title: '合同状态',
    dataIndex: 'status',
    key: 'status'
  },
  {
    title: '操作',
    dataIndex: 'inopera',
    key: 'inopera'
  }
]
const columns = [
  {
    title: '序号',
    dataIndex: 'index'
  },
  {
    title: '企业名称',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '联系人',
    dataIndex: 'contact',
    key: 'contact'
  },
  {
    title: '联系电话',
    dataIndex: 'contactNumber',
    key: 'contactNumber'
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation'
  }
]

// const dataGroups = ref([
//   {
//     groupName: '第一组',
//     groupId: 'abc001',
//     groupItem: []
//   },
//   {
//     groupName: '第二组',
//     groupId: 'abc002',
//     groupItem: []
//   },
//   {
//     groupName: '第三组',
//     groupId: 'abc003',
//     groupItem: [
//       {
//         id: 'abdszcxx',
//         name: '王五',
//         sex: '男',
//         age: 19
//       },
//       {
//         id: 'advzx',
//         name: '王五',
//         sex: '男',
//         age: 19
//       },
//       {
//         id: 'advzxxxc',
//         name: '王五',
//         sex: '男',
//         age: 19
//       }
//     ]
//   },
//   {
//     groupName: '第四组',
//     groupId: 'abc004',
//     groupItem: [
//       {
//         id: 'aaaaaav',
//         name: '赵六',
//         sex: '男',
//         age: 19
//       },
//       {
//         id: 'abdddddddd',
//         name: '赵六',
//         sex: '男',
//         age: 19
//       },
//       {
//         id: 'abvzxsad',
//         name: '赵六',
//         sex: '男',
//         age: 19
//       }
//     ]
//   }
// ])
// const outColumns = [
//   {
//     title: '小组名称',
//     dataIndex: 'groupName'
//   },
//   {
//     title: '小组ID',
//     dataIndex: 'groupId'
//   }
// ]

// const testcolumns = [
//   {
//     title: '组员姓名',
//     dataIndex: 'name'
//   },
//   {
//     title: '性别',
//     dataIndex: 'sex',
//     scopedSlots: { customRender: 'sex' }
//   },
//   {
//     title: '年龄',
//     dataIndex: 'age'
//   }
// ]
</script>

<style scoped>
.active1 {
  width: 50px;
  height: 20px;
  text-align: center;
  line-height: 20px;
  font-size: 12px;
  border: 1px solid #006ce3;
  background-color: #e5effa;
  color: #006ce3;
}
.active2 {
  width: 50px;
  height: 20px;
  text-align: center;
  line-height: 20px;
  font-size: 12px;
  border: 1px solid #209e44;
  background-color: #ebf7ee;
  color: #209e44;
}
.active3 {
  width: 50px;
  height: 20px;
  text-align: center;
  line-height: 20px;
  font-size: 12px;
  border: 1px solid #e12a19;
  background-color: #fcedea;
  color: #e12a19;
}
.active4 {
  width: 50px;
  height: 20px;
  text-align: center;
  line-height: 20px;
  font-size: 12px;
  border: 1px solid #d9d9d9;
  background-color: #fafafa;
  color: #333;
}
</style>
